﻿using System;
using System.Windows.Forms;
using System.IO;
using System.Reflection;

namespace GeneratePE {
    static class Program {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main() {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            try {
                // 加载 UserConfig.xml 配置文件
                string userConfigPath = Application.StartupPath + @"\UserConfig.xml";
                if (!File.Exists(userConfigPath)) {
                    using (StreamReader sr = new StreamReader(Assembly.GetExecutingAssembly().
                        GetManifestResourceStream(Resources.UserConfig))) {
                        using (FileStream fs = new FileStream(userConfigPath, FileMode.Create)) {
                            using (StreamWriter sw = new StreamWriter(fs)) {
                                sw.Write(sr.ReadToEnd());
                                sw.Flush();
                                sw.Close();
                            }
                            fs.Close();
                        }
                        sr.Close();
                    }
                }
                // 加载 sql client schema 文件   
                Action<string> act = s => {
                    string schemaPath = s + @"\SqlClientSchema.xml";
                    using (StreamReader sr = new StreamReader(Assembly.GetExecutingAssembly().
                            GetManifestResourceStream(Resources.SqlSchema))) {
                        using (FileStream fs = new FileStream(schemaPath, FileMode.Create)) {
                            using (StreamWriter sw = new StreamWriter(fs)) {
                                sw.Write(sr.ReadToEnd());
                                sw.Flush();
                                sw.Close();
                            }
                            fs.Close();
                        }
                        sr.Close();
                    }
                };
                if (Directory.Exists(OtherConst.SchemaFilePath)) {
                    act.Invoke(OtherConst.SchemaFilePath);
                }
                if (Directory.Exists(OtherConst.SchemaFilePath64)) {
                    act.Invoke(OtherConst.SchemaFilePath64);
                }

                Application.Run(new frmGenerate());
            }
            catch {
                string ms = "写入必要文件失败！" + Environment.NewLine;
                ms += "请确保以下两个目录有写入的权限！" + Environment.NewLine;
                ms += OtherConst.SchemaFilePath + Environment.NewLine;
                ms += OtherConst.SchemaFilePath64;
                MessageBox.Show(ms, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
